package com.molyfun.parents.activity.mineCourse;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.common.BaseActivity;
import com.molyfun.parents.activity.course.CoursePickActivity;
import com.molyfun.parents.activity.course.CourseSearchActivity;
import com.molyfun.parents.activity.coursecenter.model.SubjectListResponse;
import com.molyfun.parents.activity.store.adapter.ProductAdapter;
import com.molyfun.parents.rest.RestClient;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.uievent.UIEventListener;
import com.molyfun.parents.utils.GsonUtil;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.utils.StringUtils;
import com.molyfun.parents.view.HorizontalTagBar;
import com.molyfun.parents.view.swipeRefreshLayout.SwipeRefreshLayout;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by william(liuchao.hit@gmail.com).
 * 课程类别界面
 */
public class CourseCategoryActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, SwipeRefreshLayout.OnLoadListener,
        UIEventListener {

    public static final String FLAG_SEARCH_TAG = "search_tag";

    private static final String COURSE_CATEGORY_TYPE = "category_type";

    public static final int COURSE_CATEGORY_TYPE_HISTORY = 1001;

    public static final int COURSE_CATEGORY_TYPE_BEST = 1002;

    private int mCurrentCourseCategory = COURSE_CATEGORY_TYPE_HISTORY;

    @InjectView(R.id.search_icon)
    ImageView mSearchBtn;
    @InjectView(R.id.base_title)
    TextView mTitle;
    @InjectView(R.id.base_title_left)
    ImageView mBack;

    @InjectView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @InjectView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @InjectView(R.id.empty_layout)
    LinearLayout mEmptyLayout;
    @InjectView(R.id.pick_btn)
    TextView mPickBtn;
    @InjectView(R.id.horizontal_tag_bar)
    HorizontalTagBar mHorizontalTagBar;

    private LinearLayoutManager mLayoutManager;
    private ProductAdapter mProductAdapter;
    private int mCurrentPage = RestClient.DEFAULT_PAGE;
    private boolean mHasMoreData = true;

    private CoursePickActivity.CoursePickStorage mCoursePickStorage;

    public static final void startActivity(Context context, int type) {
        Intent intent = new Intent();
        intent.putExtra(COURSE_CATEGORY_TYPE, type);
        intent.setClass(context, CourseCategoryActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_category);
        getSupportActionBar().setTitle("");
        ButterKnife.inject(this);

        mCurrentCourseCategory = getIntent().getIntExtra(COURSE_CATEGORY_TYPE, COURSE_CATEGORY_TYPE_HISTORY);

        if (mCurrentCourseCategory == COURSE_CATEGORY_TYPE_HISTORY) {
            mTitle.setText("往期回顾");
        } else {
            mTitle.setText("精品课程");
        }

        mPickBtn.setOnClickListener(this);

        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CourseSearchActivity.startActivity(CourseCategoryActivity.this);
            }
        });

        mBack.setOnClickListener(this);

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setOnLoadListener(this);
        mSwipeRefreshLayout.setTopColor(R.color.refresh_color_01, R.color.refresh_color_02,
                R.color.refresh_color_02, R.color.refresh_color_01);
        mSwipeRefreshLayout.setBottomColor(R.color.color_transparent, R.color.color_transparent,
                R.color.color_transparent, R.color.color_transparent);
        mSwipeRefreshLayout.setMode(SwipeRefreshLayout.Mode.BOTH);
        mSwipeRefreshLayout.setLoadNoFull(true);

        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mProductAdapter = new ProductAdapter(this);
        mRecyclerView.setAdapter(mProductAdapter);

        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_COURSE_PICK, this);

        loadData(RestClient.DEFAULT_PAGE, RestClient.DEFAULT_PAGE_SIZE, true);

//        searchTopic("");

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MFPApplication.getInstance().getEventController().removeUIEventListener(EventDispatcherEnum.UI_EVENT_COURSE_PICK, this);
    }

    private void loadData(int pageNum, int pageSize, final boolean isRefresh) {

        if (isRefresh) {
            mCurrentPage = RestClient.DEFAULT_PAGE;
        }
        showProgressDialog();
        Call<SubjectListResponse> call;

        if (mCurrentCourseCategory == COURSE_CATEGORY_TYPE_HISTORY) {

            if (mCoursePickStorage != null) {
                if (!(mCoursePickStorage.getMinPrice().equals("0") && mCoursePickStorage.getMaxPrice().equals("3500"))) {
                    call = MFPApplication.getInstance().getRestClient().getSubjectList(pageNum, pageSize, mCoursePickStorage.getMaxPrice(), mCoursePickStorage.getMinPrice(), mCoursePickStorage.getmEvaluateOrder() == -1 ? "" : mCoursePickStorage.getmEvaluateOrder()+ "", mCoursePickStorage.getmCountOrder() == -1 ? "" : mCoursePickStorage.getmCountOrder() + "", StringUtils.getDate(), "", "");
                } else {
                    call = MFPApplication.getInstance().getRestClient().getSubjectList(pageNum, pageSize, "", "", mCoursePickStorage.getmEvaluateOrder() == -1 ? "" : mCoursePickStorage.getmEvaluateOrder() + "", mCoursePickStorage.getmCountOrder() == -1 ? "" : mCoursePickStorage.getmCountOrder() + "", StringUtils.getDate(), "", "");
                }

            } else {
                call = MFPApplication.getInstance().getRestClient().getSubjectList(pageNum, pageSize, "", "", "", "", StringUtils.getDate(), "", "");
            }
        } else {


            if (mCoursePickStorage != null) {
                if (!(mCoursePickStorage.getMinPrice().equals("0") && mCoursePickStorage.getMaxPrice().equals("3500"))) {
                    call = MFPApplication.getInstance().getRestClient().getSubjectList(pageNum, pageSize, mCoursePickStorage.getMaxPrice(), mCoursePickStorage.getMinPrice(), mCoursePickStorage.getmEvaluateOrder() == -1 ? "" : mCoursePickStorage.getmEvaluateOrder() + "", mCoursePickStorage.getmCountOrder() == -1 ? "" : mCoursePickStorage.getmCountOrder() + "", "", "true", "");
                } else {
                    call = MFPApplication.getInstance().getRestClient().getSubjectList(pageNum, pageSize, "", "", mCoursePickStorage.getmEvaluateOrder() == -1 ? "" : mCoursePickStorage.getmEvaluateOrder() + "", mCoursePickStorage.getmCountOrder() == -1 ? "" : mCoursePickStorage.getmCountOrder() + "", "", "true", "");
                }

            } else {
                call = MFPApplication.getInstance().getRestClient().getSubjectList(pageNum, pageSize, "", "", "", "", "", "true", "");
            }
        }
        call.enqueue(new Callback<SubjectListResponse>() {
            @Override
            public void onResponse(Call<SubjectListResponse> call, Response<SubjectListResponse> response) {
                dismissProgressDialog();
                if (response.body() != null && response.body().getData() != null) {

                    if (isRefresh) {
                        if (response.body().getData().size() > 0) {
                            mProductAdapter.refreshData(response.body().getData());
                            mHasMoreData = true;
                            mEmptyLayout.setVisibility(View.GONE);
                        } else {
                            mHasMoreData = false;
                            mProductAdapter.clearAll();
                            mEmptyLayout.setVisibility(View.VISIBLE);
                        }
                    } else {
                        if (response.body().getData().size() > 0) {
                            mHasMoreData = true;
                        } else {
                            mHasMoreData = false;
                        }
                        mProductAdapter.addAll(response.body().getData());
                    }

                }
            }

            @Override
            public void onFailure(Call<SubjectListResponse> call, Throwable t) {
                dismissProgressDialog();
            }
        });

    }

    @Override
    public void onRefresh() {
        loadData(RestClient.DEFAULT_PAGE, RestClient.DEFAULT_PAGE_SIZE, true);
        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
    }

    @Override
    public void onLoad() {
        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
        if (mHasMoreData) {
            mCurrentPage++;
            loadData(mCurrentPage, RestClient.DEFAULT_PAGE_SIZE, false);
        }
    }

    @Override
    public void handleUIEvent(Message msg) {

        switch (msg.what) {
            case EventDispatcherEnum.UI_EVENT_COURSE_PICK:
                if(msg.arg1 == CoursePickActivity.FLAG_FROM_CATEGORY){
                    mCoursePickStorage = GsonUtil.fromJson(PreferencesStorageUtil.getCCoursePickSearchStr(CourseCategoryActivity.this), CoursePickActivity.CoursePickStorage.class);
                    loadData(RestClient.DEFAULT_PAGE, RestClient.DEFAULT_PAGE_SIZE, true);
                    mHorizontalTagBar.initDataList(mCoursePickStorage.toHorizontalList());
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.base_title_left:
                finish();
                break;
            case R.id.pick_btn:

                CoursePickActivity.startActivity(CourseCategoryActivity.this, CoursePickActivity.FLAG_FROM_CATEGORY);
                break;
        }
    }

//    @Override
//    public void onSearchTagItemClick(HomelandFeaturedResponse.HotTopic hotTopic) {
//        Intent intent = new Intent();
//        intent.putExtra(FLAG_SEARCH_TAG, hotTopic.getName());
//        setResult(Activity.RESULT_OK, intent);
//        finish();
//    }

}
